'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 进入战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var Code = require('../../../consts/code');
var constantUtil = require('../../../util/constantUtil');
var bossService = require('../../../services/bossService');
var soldierService = require('../../../services/soldierService');
var bossConf = require('../../../config/bossConf');
var PlayerManager = require('../../../libs/playerManager');
var globalBossModel = require('../../../models/globalBossModel.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 当前boss的信息
 * @param  {[type]}   msg     [description]
 * @param  {[type]}   session [description]
 * @param  {Function} next    [description]
 * @return {[type]}           [description]
 */
Handler.prototype.info = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var global_boss_model;
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['boss', 'soldier', 'accrued'],
                    cb);
            },
            function (cb) {
                globalBossModel.getGlobalBossInfo(function (err, model) {
                    global_boss_model = model;
                    if (!model) {
                        return next(null, {
                            code: Code.DATABASE_SAVE_ERROR
                        });
                    }
                    cb();
                });
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            var boss_model = player_manager.boss;
            var soldier_model = player_manager.soldier;
            var boss_conf = bossConf.getTodayBossConf();
            return next(null, {
                code: Code.OK,
                result: {
                    boss_id: global_boss_model.boss_id,
                    battle_num: boss_model.getBattleNum(),
                    max_battle_num: constantUtil.value('boss_challenge_times'),
                    is_open: +bossService.isCanEnter(),
                    next_open_time: moment(bossService.nextOpenTime()).unix(),
                    select_soldier_list: boss_model.select_soldier_list,
                    boss_soldier_power: soldierService.calcSoldierPower(soldier_model, boss_model.select_soldier_list)
                }
            });
        }
    );
};
